/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.oai.metadataRepository.repository.records.impl;

import cz.mzk.oai.metadataRepository.metadata.DateStamp;
import cz.mzk.oai.metadataRepository.metadata.MetadataFormat;
import cz.mzk.oai.metadataRepository.repository.Identifier;
import cz.mzk.oai.metadataRepository.repository.OaiSet;
import cz.mzk.oai.metadataRepository.repository.collections.MetadataCollection;
import cz.mzk.oai.metadataRepository.repository.records.Record;
import java.io.File;
import java.util.Set;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public abstract class AbstractFileRecord implements Record {

    private final Identifier identifier;
    protected final MetadataFormat format;
    protected final MetadataCollection collection;
    private File metadataFile = null;//lazy loaded
    private final File metadataDir;

    public AbstractFileRecord(Identifier identifier, MetadataFormat format, File metadataDir, MetadataCollection collection) {
        this.identifier = identifier;
        this.format = format;
        this.metadataDir = metadataDir;
        this.collection = collection;
    }

    public Identifier getId() {
        return identifier;
    }

    public Set<OaiSet> getOaiSets() {
        return collection.getOaiSets();
    }

    public MetadataFormat getMetadataFormat() {
        return format;
    }

    public DateStamp getDateStamp() {
        File file = getMetadataFile();
        long lastModified = file.lastModified();
        return DateStamp.fromMilliseconds(lastModified);
    }

    File getMetadataFile() {
        if (metadataFile == null) {
            buildMetadataFile();
            //System.err.println("building file " + metadataFile.getAbsolutePath());
        }
        return metadataFile;
    }

    private void buildMetadataFile() {
        String absoluteFilename = metadataDir + File.separator
                + identifier.toFilename();
        metadataFile = new File(absoluteFilename);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final AbstractFileRecord other = (AbstractFileRecord) obj;
        if (this.identifier != other.identifier && (this.identifier == null || !this.identifier.equals(other.identifier))) {
            return false;
        }
        if (this.format != other.format) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 59 * hash + (this.identifier != null ? this.identifier.hashCode() : 0);
        hash = 59 * hash + (this.format != null ? this.format.hashCode() : 0);
        return hash;
    }
}
